package com.company.emallbackend.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.emallbackend.common.AliPayConfig;
import com.company.emallbackend.entity.*;
import com.company.emallbackend.entity.dto.CartDTO;
import com.company.emallbackend.entity.dto.OrderDTO;
import com.company.emallbackend.exception.CommonException;
import com.company.emallbackend.mapper.OrderMapper;
import com.company.emallbackend.mapper.ProductMapper;
import com.company.emallbackend.mapper.ProductOrderMapper;
import com.company.emallbackend.service.IOrderService;
import com.company.emallbackend.utils.AliPayUtil;
import com.company.emallbackend.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hanlijian
 * @since 2023-01-12
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private AliPayConfig aliPayConfig;
    
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ProductOrderMapper productOrderMapper;
    @Resource
    private ProductMapper productMapper;

    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Override
    public void addOrder(OrderDTO orderDTO, HttpServletResponse response) {
        if(Objects.isNull(orderDTO)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        List<CartDTO> cartDTOList = orderDTO.getCartDTOList();
        String linkAddress = orderDTO.getLinkAddress();
        String linkPhone = orderDTO.getLinkPhone();
        if(CollectionUtils.isEmpty(cartDTOList) || StrUtil.isBlank(linkAddress) || StrUtil.isBlank(linkPhone)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        String orderNumber= DateUtil.format(new Date(),"yyyyMMdd")+System.currentTimeMillis();
        Order order = new Order();
        order.setOrderNo(orderNumber);
        order.setUserId(TokenUtils.getCurrentAdmin().getId());
        order.setLinkAddress(linkAddress);
        order.setLinkPhone(linkPhone);
        //添加Order表数据
        orderMapper.insert(order);
        BigDecimal totalPrice=new BigDecimal("0.0");
        for (CartDTO cartDTO : cartDTOList) {
            Integer productId = cartDTO.getProductId();
            Integer count = cartDTO.getCount();
            //根据商品id查询商品库存是否够
            Product product=this.findCountEnough(productId,count);
            if(Objects.nonNull(product)){
                //根据商品id查询商品价格
                BigDecimal price = product.getPrice();
                totalPrice=totalPrice.add(price.multiply(new BigDecimal(count)));
                Integer orderId = order.getId();
                productOrderMapper.insert(new ProductOrder(orderId,productId,count.longValue()));
            }
        }
        order.setTotalPrice(totalPrice);
        orderMapper.updateById(order);
        AliPay aliPay = new AliPay(orderNumber,totalPrice.doubleValue(),"待支付商品",cartDTOList);
        AliPayUtil.sendRequestToAliPay(aliPayConfig,aliPay,response);
    }
    
    //根据商品id查询商品库存是否够
    private Product findCountEnough(Integer productId, Integer count) {
        if(Objects.isNull(productId) || Objects.isNull(count)){
            throw new CommonException(201,"请检查您要下单的商品");
        }
        Product product = productMapper.selectById(productId);
        Long store = product.getStore();
        if(count>store){
            throw new CommonException(201,product.getName()+"库存不足");
        }
        return product;
    }

    public void pay(AliPay aliPay,HttpServletResponse response){
        try {
            // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

            // 2. 创建 Request并设置Request参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
            request.setNotifyUrl(aliPayConfig.getNotifyUrl());
            JSONObject bizContent = new JSONObject();
            bizContent.set("out_trade_no", aliPay.getTradeNo());  // 我们自己生成的订单编号
            bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额
            bizContent.set("subject", aliPay.getSubject());   // 支付的名称
            bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
            request.setBizContent(bizContent.toString());

            // 执行请求，拿到响应的结果，返回给浏览器
            String form = "";
            try {
                form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            response.setContentType("text/html;charset=" + CHARSET);
            response.getWriter().write(form);// 直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
    }
    @Override
    public List<Order> getMyOrderList() {
        User user = TokenUtils.getCurrentAdmin();
        Integer userId = user.getId();
        //根据userId查询订单列表
        List<Order> orderList = orderMapper.selectList(new QueryWrapper<Order>().eq("user_id", userId));
        for (Order order : orderList) {
            Integer orderId = order.getId();
            //根据orderId查询product_order表
            List<ProductOrder> productOrderList = productOrderMapper.selectList(new QueryWrapper<ProductOrder>().eq("order_id", orderId));
            order.setProductOrderList(productOrderList);
        }
        return orderList;
    }

    @Override
    public void payNotify(HttpServletRequest request) {
        try {
            if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
                System.out.println("=========支付宝异步回调========");
    
                Map<String, String> params = new HashMap<>();
                Map<String, String[]> requestParams = request.getParameterMap();
                for (String name : requestParams.keySet()) {
                    params.put(name, request.getParameter(name));
                    // System.out.println(name + " = " + request.getParameter(name));
                }
                String outTradeNo = params.get("out_trade_no");
                String gmtPayment = params.get("gmt_payment");
                String alipayTradeNo = params.get("trade_no");
                String totalAmount = params.get("total_amount");
                String passback_params = params.get("passback_params");
                if(StrUtil.isBlank(outTradeNo) || StrUtil.isBlank(gmtPayment) || StrUtil.isBlank(alipayTradeNo) || StrUtil.isBlank(totalAmount)){
                    throw new CommonException(201,"系统繁忙,稍后再试");
                }
                String[] split = passback_params.split("-");
                List<CartDTO> cartDTOList=new ArrayList<>();
                for (String s : split) {
                    //1,3
                    //2,2
                    //3,1
                    String[] split1 = s.split(",");
                    CartDTO cartDTO = new CartDTO();
                    cartDTO.setProductId(Integer.parseInt(split1[0]));
                    cartDTO.setCount(Integer.parseInt(split1[1]));
                    cartDTOList.add(cartDTO);
                }
                String sign = params.get("sign");
                String content = AlipaySignature.getSignCheckContentV1(params);
                boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
                // 支付宝验签
                if (checkSignature) {
                    // 验签通过
                    System.out.println("交易名称: " + params.get("subject"));
                    System.out.println("交易状态: " + params.get("trade_status"));
                    System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                    System.out.println("商户订单号: " + params.get("out_trade_no"));
                    System.out.println("交易金额: " + params.get("total_amount"));
                    System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                    System.out.println("买家付款时间: " + params.get("gmt_payment"));
                    System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                    //对支付结果做二次校验
                    Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_no", outTradeNo));
                    if(Objects.isNull(order)){
                        throw new CommonException(201,"订单不存在");
                    }
                    //校验金额是否正确
                    if(order.getTotalPrice().compareTo(new BigDecimal(totalAmount))!=0){
                        throw new CommonException(201,"金额校验失败");
                    }
                    //处理订单
                    this.processOrder(cartDTOList,gmtPayment,alipayTradeNo,outTradeNo);
                }else {
                    throw new CommonException(201,"支付失败");
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String queryOrder(String orderNo) {
        try {
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no",orderNo);
            request.setBizContent(bizContent.toString());
            AlipayClient alipayClient = AliPayUtil.getAlipayClient(aliPayConfig);
            AlipayTradePagePayResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                log.info("调用成功 ===>" + response.getBody());
                return response.getBody();
            } else {
                log.info("调用失败 ===>" + response.getCode() + "，返回描述 ===>" + response.getMsg());
                return null;
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new CommonException(201,"查询订单失败");
        }
    }

    @Override
    public List<Order> queryPayOrder() {
        List<Order> orderList = orderMapper.selectList(new QueryWrapper<Order>().eq("state", 1));
        return orderList;
    }

    @Override
    public void deliverGoods(Integer orderId) {
        if(Objects.isNull(orderId)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        Order order = orderMapper.selectById(orderId);
        if(Objects.isNull(order) || order.getState()!=1){
            throw new CommonException(201,"订单异常");
        }
        order.setState(2);
        orderMapper.updateById(order); 
    }

    public void processOrder(List<CartDTO> cartDTOList, String gmtPayment, String alipayTradeNo, String outTradeNo) {
        if(CollectionUtils.isEmpty(cartDTOList)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        for (CartDTO cartDTO : cartDTOList) {
            Integer productId = cartDTO.getProductId();
            Integer count = cartDTO.getCount();
            this.updateProductStore(productId,count);
        }
        //根据订单号查询订单表
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_no", outTradeNo));
        order.setTradeNo(alipayTradeNo);
        order.setState(1);
        order.setUpdateTime(DateUtil.parse(gmtPayment,"yyyy-MM-dd HH:mm:ss"));
        orderMapper.updateById(order);
    }

    /**
     * 根据商品id和数量修改数据库
     * @param productId
     * @param count
     */
    private void updateProductStore(Integer productId, Integer count) {
        Product product = productMapper.selectById(productId);
        if(Objects.isNull(product)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        Long store = product.getStore();
        if(count>store){
            throw new CommonException(201,"库存不足");
        }
        //更新商品库存
        product.setStore(store-count);
        productMapper.updateById(product);
    }

}
